package cn.neusoft.yp.service.impl;

import cn.neusoft.yp.mapper.ProdMapper;
import cn.neusoft.yp.pojo.Page;
import cn.neusoft.yp.pojo.Product;
import cn.neusoft.yp.service.ProdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * Created by gaosheng on 2017/4/27.
 */
@Service
public class ProdServiceImpl implements ProdService {

    @Autowired
    private ProdMapper prodMapper;

    public Page<Product> findAll(int thispage, int rowperpage, String name,
                                 String category, Double minprice, Double maxprice) {
        Page<Product> page = new Page<Product>() ;
        //封装查询条件类型
        page.setName(name.trim());
        page.setCategory(category.trim());
        if(minprice!=-1){
            page.setMinprice(minprice);
        }
        if(maxprice!=Double.MAX_VALUE){
            page.setMaxprice(maxprice);
        }
        //封装分页相关
        page.setThispage(thispage);
        page.setRowperpage(rowperpage);
        //封装商品总数-总行数
        int countrow = prodMapper.findNumByKey(name, category, minprice, maxprice);
            page.setCountrow(countrow);
        //计算中页数
        //总页数
        int countpage = countrow/rowperpage + (countrow%rowperpage==0?0:1);
        page.setCountpage(countpage);
        //设置上一页
        page.setPrepage(thispage==1?1:thispage-1);
        //设置下一页
        page.setNextpage(thispage==countpage?countpage:thispage+1);
        //当前页的所有商品的信息  limit m,n
        page.setList(prodMapper.findAll((thispage-1)*rowperpage,rowperpage,name.trim(),category.trim(),minprice,maxprice)
        );
        return page;
    }

    public Product findOne(String id) {
        return prodMapper.findOne(id);
    }

    public List<Product> findProd(int prepage, int nextpage) {
        return prodMapper.findProd(prepage,nextpage);
    }

    public List<Product> findprod() {
        return prodMapper.findprod();
    }

    public void addProd(Product prod) {
        prodMapper.addProd(prod);
    }

    public void deleteProd(String id) {
        prodMapper.deleteProd(id);
    }

    public Page toPage(int thispage, int rowperpage) {
        Page page = new Page();
        //分装分页相关
        page.setThispage(thispage);
        page.setRowperpage(rowperpage);
        //总行数
        int countrow = prodMapper.findNum() ;

        page.setCountrow(countrow);
        //总页数
        int countpage = countrow/rowperpage + (countrow%rowperpage==0?0:1);
//        int countpage = countrow/rowperpage;
        page.setCountpage(countpage);
        //设置上一页
        page.setPrepage(10*thispage-10);
        //设置下一页
        page.setNextpage(rowperpage);

        return page;
    }
}
